package com.yztc.orangeentertainment.ui.main.channalfragment;

import android.annotation.TargetApi;
import android.app.Service;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.yztc.orangeentertainment.R;
import com.yztc.orangeentertainment.adapter.ChannalPopupWindowAdapter;
import com.yztc.orangeentertainment.adapter.MyFagmentListAdapter;
import com.yztc.orangeentertainment.base.BaseFragment;
import com.yztc.orangeentertainment.base.OnItemClickListener;
import com.yztc.orangeentertainment.bean.channalbean.ChannalTitleDataBean;
import com.yztc.orangeentertainment.ui.main.channalcontentfragment.ChannalContentFragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by My on 2016/10/5.
 */
public class ChannalFragment extends BaseFragment implements ChannalContract.View {
    @InjectView(R.id.tab_channal)
    TabLayout tabChannal;
    @InjectView(R.id.iv_channal)
    ImageView ivChannal;
    @InjectView(R.id.vp_channal)
    ViewPager vpChannal;
    @InjectView(R.id.ll_channalmain)
    RelativeLayout llChannalmain;
    private RecyclerView rvChannalpopwin;
    private List<Fragment> fragmentList = new ArrayList<>();
    private List<ChannalTitleDataBean> channalTitles;
    private ChannalContract.Presenter presenter;
    private int mDistanceY;
    private int dragFlags;
    private MyFagmentListAdapter adapter1;
    private int swipeFlags;
    private ItemTouchHelper itemTouchHelper;
    private PopupWindow popupWindow;
    private ChannalPopupWindowAdapter adapter;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_channal;
    }


    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        final View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.inject(this, rootView);
        initData(rootView);

        return rootView;
    }
    //从网络获取数据
    private void initData(final View rootView) {
        presenter = new ChannalPresenter(this);
        presenter.getChannalTitleFromNet();
        ivChannal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.iv_channal:
                        if (popupWindow != null && popupWindow.isShowing()) {
                            popupWindow.dismiss();
                            return;
                        } else {
                            initmPopupWindowView(rootView);
                            initmPopupWindowViewData();
                            popupWindow.showAtLocation(rootView, Gravity.FILL,0,0);
                        }
                        break;
                }
            }
        });
    }
    //popupwindow数据的装载
    private void initmPopupWindowViewData() {
        adapter = new ChannalPopupWindowAdapter(getActivity(),
                channalTitles);
        rvChannalpopwin.setAdapter(adapter);
        adapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                vpChannal.setCurrentItem(position);
                popupWindow.dismiss();
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
    }
    //实例化popupwindow中的控件
    private void initmPopupWindowView(View rootView) {
        View customView = LayoutInflater.from(getActivity()).inflate(R.layout
                .channal_contentpopupwindow,null);
        popupWindow = new PopupWindow(customView, ViewPager.LayoutParams.MATCH_PARENT, ViewPager
                .LayoutParams.MATCH_PARENT);
        //设置popupwindow进出动画
        popupWindow.setAnimationStyle(R.style.AnimationFade);
        customView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        rvChannalpopwin = (RecyclerView) customView.findViewById(R.id.rv_channalpopwin);
        rvChannalpopwin.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                //获取震动服务
                Vibrator vibrator = (Vibrator) getActivity().getSystemService(Service.VIBRATOR_SERVICE);
                //震动多长时间
                vibrator.vibrate(70);
                //设置recycleview中的数据可以向哪边拖动
                if (rvChannalpopwin.getLayoutManager() instanceof GridLayoutManager) {
                    dragFlags = ItemTouchHelper.UP |
                            ItemTouchHelper.DOWN |
                            ItemTouchHelper.LEFT |
                            ItemTouchHelper.RIGHT|
                            ItemTouchHelper.ACTION_STATE_SWIPE;
                    swipeFlags = 0;


                } else {
                    dragFlags = ItemTouchHelper.UP |
                            ItemTouchHelper.DOWN;
                    swipeFlags = 0;
                }
                return makeMovementFlags(dragFlags, swipeFlags);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                int fromPosition = viewHolder.getAdapterPosition();
                int toPosition = target.getAdapterPosition();
                //调换list集合数据的位置
                Collections.swap(channalTitles, fromPosition, toPosition);
                //刷新adapter中的数据
                adapter.notifyItemChanged(fromPosition, toPosition);
                initmPopupWindowViewData();
                Collections.swap(fragmentList,fromPosition,toPosition);
                initTabTitle(channalTitles);
                adapter1.notifyDataSetChanged();
                return true;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {

            }
        });
        //绑定控件
        itemTouchHelper.attachToRecyclerView(rvChannalpopwin);
    }
    //给viewpager中的每一个fragment传递数据
    private void inittitle() {
        if(fragmentList.size()>0){
            fragmentList.removeAll(fragmentList);
        }
        for (int i = 0; i < channalTitles.size(); i++) {
            ChannalContentFragment f1 = new ChannalContentFragment();
            Bundle bundle = new Bundle();
            bundle.putInt("id",channalTitles.get(i).getId());
            f1.setArguments(bundle);
            fragmentList.add(f1);
        }
        adapter1 = new MyFagmentListAdapter(getFragmentManager(), fragmentList);
        adapter1.notifyDataSetChanged();
        vpChannal.setAdapter(adapter1);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }
    //获取tablayout标签的数据
    @Override
    public void onChannalTitleSucess(List<ChannalTitleDataBean> channalTitleList) {
        channalTitles = new ArrayList<>();
        channalTitles = channalTitleList;
        initTabTitle(channalTitles);
    }
    //给tablayout中的tab适配数据
    private void initTabTitle(List<ChannalTitleDataBean> channalTitleList) {
        tabChannal.removeAllTabs();
        tabChannal.setTabTextColors(Color.WHITE, Color.YELLOW);
        for (int i = 0; i < channalTitleList.size(); i++) {
            tabChannal.addTab(tabChannal.newTab().setText(channalTitleList.get(i).getName()));
        }
        inittitle();
        //将viewpager和tablayout进行绑定
        vpChannal.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabChannal));
        tabChannal.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                vpChannal.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public void onChannalTitleFail(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
    }
}
